#include "Direct3DFramework.h"

int Direct3DFramework::updateCamera(V2DF a_camPos)
{
	m_camPos.x = (m_window->m_windowWidth/2.0f) - a_camPos.x;
	m_camPos.y = (m_window->m_windowHeight/2.0f) - a_camPos.y;
	return GPX_SUCCESS;
}

bool within(V2DF minA, V2DF maxA, V2DF minB, V2DF maxB)
{
	if(maxA.x < minB.x ||
		minA.x > maxB.x ||
		maxA.y < minB.y ||
		minA.y > maxB.y)
		return false;
	return true;
}

int Direct3DFramework::updateTransform(BeanieTexture* a_texture,
	V2DF a_transform, V2DF a_scale, float a_rotate,
	V2DF* a_pos, V2DF* a_min, V2DF* a_max)
{
	//culling check
	V2DF minA(
		-m_camPos.x,
		-m_camPos.y);
	V2DF maxA(
		(-m_camPos.x+(m_window->m_windowWidth)),
		(-m_camPos.y+m_window->m_windowHeight));

	m_camMin = minA;
	m_camMax = maxA;

	minA += *a_min;
	maxA += *a_max;

	if(a_pos != 0)
	{
		V2DF min = (*a_pos) + (*a_min);
		V2DF max = (*a_pos) + (*a_max);
		if(!within(min,max,minA,maxA))
		{
			a_texture->m_culling = true;
			return GPX_SUCCESS;
		}
		else
			a_texture->m_culling = false;
	}

	//get texture with given id
	D3DFTexture* texture = m_textureList[a_texture->m_texId];

	//empty matrices
	D3DXMatrixIdentity(&m_camMat);
	D3DXMatrixIdentity(&texture->m_matrices[a_texture->m_matId].m_scale);
	D3DXMatrixIdentity(&texture->m_matrices[a_texture->m_matId].m_rotate);
	D3DXMatrixIdentity(&texture->m_matrices[a_texture->m_matId].m_translate);
	D3DXMatrixIdentity(&texture->m_matrices[a_texture->m_matId].m_world);

	//create scaling matrix
	D3DXMatrixScaling(&texture->m_matrices[a_texture->m_matId].m_scale,
		a_scale.x,a_scale.y,1.0f);

	//create rotation matrixs
	D3DXMatrixRotationZ(&texture->m_matrices[a_texture->m_matId].m_rotate,
		D3DXToRadian(a_rotate));

	//create translation matrix
	D3DXMatrixTranslation(&texture->m_matrices[a_texture->m_matId].m_translate,
		a_transform.x,a_transform.y,0.0f);

	//translate to camera view
	if(!a_texture->m_camLock)
		D3DXMatrixTranslation(&m_camMat,m_camPos.x,m_camPos.y,0.0f);
	
	//create world matrix
	texture->m_matrices[a_texture->m_matId].m_world = 
		(texture->m_matrices[a_texture->m_matId].m_scale
		*texture->m_matrices[a_texture->m_matId].m_rotate * m_camMat
		*texture->m_matrices[a_texture->m_matId].m_translate);

	return GPX_SUCCESS;
}